package com.jeeww.web;

import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.jeeww.core.utils.AgileUtils;
import com.alibaba.fastjson.JSONObject;
import com.jeeww.core.CommonConstants;

/**
 * 功能描述：controller父类.
 */
@Controller
public class BaseController {
    /**
     * logger.
     */
    private Logger logger = Logger.getLogger(BaseController.class);

    /**
     * 功能描述 :获取国际化消息值.
     * @param req req.
     * @param messageKey messageKey.
     * @return String 返回国际化消息值.
     * @throws Exception e.
     */
    public String getLocalMsg(final HttpServletRequest req, final String messageKey) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("获取国际化消息值key：" + messageKey);
        }
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        Locale locale = RequestContextUtils.getLocaleResolver(req).resolveLocale(req);
        String message = webApplicationContext.getMessage(messageKey, null, "默认值", locale);
        return message;
    }

    /**
     * 功能描述 :获取国际化消息值.
     * @param req req.
     * @param messageJSONObject messageJSONObject.
     * @return String 返回国际化消息值.
     * @throws Exception e.
     */
    public String getLocalMsg(final HttpServletRequest req, final JSONObject messageJSONObject) throws Exception {
        Object msgKey = messageJSONObject.get(CommonConstants.MSG_KEY);
        if (msgKey != null && !msgKey.equals("")) {
            String message = getLocalMsg(req, msgKey.toString());
            Object msgParams = messageJSONObject.get(CommonConstants.MSG_PARAMS);
            if (msgParams != null && !"".equals(msgParams)) {
                String newMsg = AgileUtils.stringEvaluate(message,
                        (JSONObject) messageJSONObject.get(CommonConstants.MSG_PARAMS));
                messageJSONObject.put(CommonConstants.MSG_INFO, newMsg);
            } else {
                messageJSONObject.put(CommonConstants.MSG_INFO, message);
            }
            return JSONObject.toJSONString(messageJSONObject);
        }
        return null;
    }
}
